package com.zhouixi.reproduce.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import com.zhouixi.reproduce.config.DataSourceContextHolder;
import com.zhouixi.reproduce.service.DataSources;
import lombok.extern.slf4j.Slf4j;

@Aspect
@Component
@Slf4j
public class DynamicDataSourceAspect {

	String master = "insert,add,update";

	@Pointcut("execution(* com.zhouixi.reproduce.service.impl.*.*(..))")
	public void daoAspect() {

	}

	@Before("DynamicDataSourceAspect.daoAspect()")
	public void beforeChangeDB(JoinPoint point) {

		boolean isQueryMethod = isQueryMethod(point.getSignature().getName());
		if (isQueryMethod) {
			DataSourceContextHolder.setDB(DataSources.SLAVE_DB);
			log.info("Switch DataSource to [{}] in Method [{}]", DataSourceContextHolder.getDB(), point.getSignature());
		} else {
			// 切换数据源
			if(DataSourceContextHolder.getDB().equals(DataSources.SLAVE_DB)) {
				DataSourceContextHolder.setDB(DataSources.MASTER_DB);
			}
		}
	}

	@After("daoAspect()")
	public void afterClearDB(JoinPoint point) {
		DataSourceContextHolder.clearDB();
		log.info("数据库恢复到主库");
	}

	private Boolean isQueryMethod(String methodName) {
		String[] split = master.split(",");
		for (String name : split) {
			if (methodName.equals(name)) {
				return false;
			}
		}
		return true;
	}
}
